package com.xjc.infra.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * HttpServletRequest工具类
 * @author lqf
 * @date 2016年11月17日 下午2:45:56
 */
public class HttpServletRequestUtil {
	
	private static Logger logger = Logger.getLogger(HttpServletRequestUtil.class);
	
	
	
	/**
	 * 获取当前请求request
	 * @author lqf 
	 * @Date 2017/7/10
	 * @return
	 */
	public static HttpServletRequest getHttpServletRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		return request;
	}

	/**
	 * 获取当前请求session
	 * @author lqf 
	 * @Date 2017/7/10
	 * @return
	 */
	public static HttpSession getHttpSession() {
		return getHttpServletRequest().getSession();
	}
	    
	/**
	 * 获取访问者IP
	 * @author lqf 
	 * @date 2016年11月17日 下午2:45:47
	 * @param request
	 * @return
	 */
	public static String getRequestIP(HttpServletRequest request){
		try {
			String ip = request.getHeader("x-forwarded-for");
		    if(ip == null || ip.trim().length() == 0 || "unknown".equalsIgnoreCase(ip)){
		        ip = request.getHeader("Proxy-Client-IP");
		    }
		    if(ip == null || ip.trim().length() == 0 || "unknown".equalsIgnoreCase(ip)){
		        ip = request.getHeader("WL-Proxy-Client-IP");
		    }
		    if(ip == null || ip.trim().length() == 0 || "unknown".equalsIgnoreCase(ip)){
		        ip = request.getRemoteAddr();
		    }
		    return "0:0:0:0:0:0:0:1".equals(ip)?"127.0.0.1":ip;
		} catch (Exception e) {
			logger.error("ip地址获取失败",e);
			return null;
		}
	}
	
	/**
	 * 系统访问源  如：电脑、IOS、Andrion
	 * @param request
	 * @return
	 * @date 2016年6月22日
	 * @author lqf
	 */
	public static String getAccessSouce(HttpServletRequest request){
		String accessSouce = "PC";
		String[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };  
		try {
			String agent =getBrowserType(request).toLowerCase();
			//Windows 桌面系统    
			if ((agent.indexOf("windows nt") > -1) && agent.indexOf("compatible; msie 9.0;") <= -1) {    
				return  "WINDOWS-PC";
			}else if (agent.indexOf("windows nt") > -1 && agent.indexOf("macintosh") > -1 ) {  
				return "IOS-PC";
			}
			for (String item : keywords) {    
				if (agent.toLowerCase().indexOf(item.toLowerCase())>-1) {    
					return item;
				}  
			}
			return accessSouce;
		} catch (Exception e) {
			logger.error("系统访问源获取失败",e);
			return null;
		}
	}
	
	/**
	 * 获取访问源类型即浏览器类型
	 * @author lqf 
	 * @date 2016年11月17日 下午2:52:13
	 * @param request
	 * @return
	 */
	public static String getBrowserType(HttpServletRequest request){
		try {
			return request.getHeaders("User-Agent").nextElement().toString();
		} catch (Exception e) {
			logger.error("浏览器类型获取失败",e);
			return null;
		}
	}
}
